package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.domain.Category;
import com.jiawa.wiki.domain.CategoryExample;
import com.jiawa.wiki.mapper.CategoryMapper;
import com.jiawa.wiki.req.CategoryQueryReq;
import com.jiawa.wiki.resp.CategoryQueryResp;
import com.jiawa.wiki.resp.PageResp;
import com.jiawa.wiki.utill.CopyUtil;
import com.jiawa.wiki.utill.SnowFlake;
import org.apache.ibatis.annotations.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryService {
    private final static Logger LOG = LoggerFactory.getLogger(CategoryService.class);

    @Resource
    CategoryMapper categoryMapper;
    @Autowired
    private SnowFlake snowFlake;
    //全部展示不分页
    public List<CategoryQueryResp> all() {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");//排序功能
        List<Category> categories = categoryMapper.selectByExample(categoryExample);

        List<CategoryQueryResp> categoryQueryRespList = CopyUtil.copyList(categories, CategoryQueryResp.class);
        return categoryQueryRespList;
    }

    //查询+展示
    public PageResp<CategoryQueryResp> list(CategoryQueryReq req) {
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Category> categories = categoryMapper.selectByExample(categoryExample);
        List<CategoryQueryResp> categoryQueryRespList = CopyUtil.copyList(categories, CategoryQueryResp.class);
        PageInfo<Category> info = new PageInfo(categories);
        PageResp<CategoryQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(info.getTotal());
        pageResp.setList(categoryQueryRespList);
        return pageResp;
    }
    //编辑+新增
    public void  save(CategoryQueryReq req){
        Category category = CopyUtil.copy(req, Category.class);
        if (ObjectUtils.isEmpty(category.getId())){
             category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        }else{
            categoryMapper.updateByPrimaryKey(category);
        }

    }
    //删除
    public void delete(Long  id){
        categoryMapper.deleteByPrimaryKey(id);
    }


}
